<?php
class CmsBlockModel extends Model
{
    protected $resourceId = 'AdminResource';
    protected static $instance;

    public static function GetInstance()
    {
        return self::$instance ? self::$instance : self::$instance = new CmsBlockModel();
    }

    protected function LoadFields()
    {
        parent::LoadFields();
        $this->SetForeignKey('page_id', CmsPageModel::GetInstance()->GetTableName(), 'id');
        $this->SetForeignKey('position', CmsBlockPositionModel::GetInstance()->GetTableName(), 'id');
        $this->SetForeignKey('block_type', CmsBlockTypeModel::GetInstance()->GetTableName(), 'id');
    }

    public function Insert($item)
    {
        $id = parent::Insert($item);
        if (isset($item['name']))
    {
            $this->CreateElementFile($item);
        }
        return $id;
    }

    public function Update($item)
    {
        if (isset($item['name'])) $oldBlockId = $this->FindScalarById($item['id'], 'name');

        $id = parent::Update($item);
        if (isset($item['name']))
    {
            $block = $this->FindById($id);
            $this->CreateElementFile($block, $oldBlockId);
    }
        return $id;
    }

    protected function CreateElementFile($item, $oldBlockId = null)
    {
        $blockId = $item['name'];
        $blockTypeId = array_get($item, 'block_type');
        if ($blockTypeId == CmsBlockTypeModel::$BLOCKTYPE_ELEMENT)
        {
            $pageId = array_get($item, 'page_id');
            $layout = CmsPageModel::GetInstance()->GetLayoutById($pageId);
            if (!$layout) throw new Exception('Page layout is missing');
            $layout = new $layout();
            $config = $layout->GetConfig();
            $file = $config->DIR_HTML_ELEMENTS.DS.$blockId;
            if (!file_exists($file))
            {
                $oldFile = $config->DIR_HTML_ELEMENTS.DS.$oldBlockId;
                if ($oldBlockId && file_exists($oldFile))
                {
                    rename($oldFile, $file);
                    MessageBase::Confirm("Renamed file '$oldFile' to '$file'");
                }
                else
                {
                    FileHandler::Write($file, '');
                    MessageBase::Confirm("Created file '$file'");
                }
        }
            else Messagebase::Warning("Element file '$file' already existed");
        }
    }

    public function GetElementFile($item)
    {
        $blockId = $item['name'];
        $pageId = array_get($item, 'page_id');
        $layout = CmsPageModel::GetInstance()->GetLayoutById($pageId);
        if (!$layout) throw new Exception('Page layout is missing');
        $layout = new $layout();
        $config = $layout->GetConfig();
        $file = $config->DIR_HTML_ELEMENTS.DS.$blockId;
        return FileHandler::Read($file);
    }
}
?>
